package com.bestcem.xm.common.core.uitls;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.util.function.Supplier;

/**
 * @author zhangfeng <feng.zhang@idiaoyan.com>
 * @version v1.0
 * @date 2022/7/19 21:06
 */
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class TransactionUtils {

    public static boolean doTransaction(PlatformTransactionManager transactionManager,
                                        Supplier<Boolean> supplier,
                                        TransactionDefinition transactionDefinition) {
        TransactionStatus status = transactionManager.getTransaction(transactionDefinition);
        try {
            if (supplier.get()) {
                transactionManager.commit(status);
                return true;
            } else {
                transactionManager.rollback(status);
                return false;
            }
        } catch (Exception e) {
            log.error("[XM] 事务保存异常，进行回滚", e);
            transactionManager.rollback(status);
            throw e;
        }
    }

    public static boolean doTransaction(PlatformTransactionManager transactionManager, Supplier<Boolean> supplier) {
        return doTransaction(transactionManager, supplier, new DefaultTransactionDefinition());
    }
}
